/**
 * Ollama 设置对话框组件
 * 负责管理设置对话框的显示、交互和数据管理
 */
class SettingsModel {
  constructor() {
    this.model = null;
    this.isInitialized = false;
    this.settings = null;
  }

  /**
   * 初始化设置对话框
   */
  async init() {
    if (this.isInitialized) return;

    try {
      // 加载HTML组件
      await this.loadComponent();      // 绑定事件监听器
      this.bindEvents();
      
      // 先自动加载配置文件（从后端获取包含app.js配置的设置）
      await this.loadConfigFromFile();
      
      // 然后加载本地保存的设置（可能会覆盖部分配置）
      this.loadSettings();

      // 初始化模型列表
      await this.refreshModels();

      this.isInitialized = true;
      console.log('设置对话框初始化完成');
    } catch (error) {
      console.error('设置对话框初始化失败:', error);
    }
  }
  /**
   * 加载HTML组件
   */
  async loadComponent() {
    try {
      const response = await fetch('./components/settings-model.html');
      const html = await response.text();

      // 将组件HTML插入到页面中
      document.body.insertAdjacentHTML('beforeend', html);

      this.model = document.getElementById('settings-model');
    } catch (error) {
      console.error('加载设置组件失败:', error);
      throw error;
    }
  }

  /**
   * 绑定事件监听器
   */
  bindEvents() {
    // 关闭按钮事件
    const closeBtn = this.model.querySelector('.close');
    closeBtn.addEventListener('click', () => this.hide());

    // 点击遮罩层关闭
    this.model.addEventListener('click', (e) => {
      if (e.target === this.model) {
        this.hide();
      }
    });

    // 刷新模型按钮
    const refreshBtn = this.model.querySelector('#refresh-models-btn');
    refreshBtn.addEventListener('click', () => this.refreshModels());

    // 温度滑块事件
    const temperatureInput = this.model.querySelector('#temperature-input');
    const temperatureValue = this.model.querySelector('#temperature-value');
    temperatureInput.addEventListener('input', (e) => {
      temperatureValue.textContent = e.target.value;
      this.settings.ollama.parameters.temperature = parseFloat(e.target.value);
    });

    // 最大长度输入事件
    const maxLengthInput = this.model.querySelector('#max-length-input');
    maxLengthInput.addEventListener('input', (e) => {
      this.settings.ollama.parameters.max_length = parseInt(e.target.value);
    });

    // 模型选择事件
    const modelSelect = this.model.querySelector('#model-select');
    modelSelect.addEventListener('change', (e) => {
      this.settings.ollama.model = e.target.value;
    });

    // 保存设置按钮
    const saveBtn = this.model.querySelector('#save-settings-btn');
    saveBtn.addEventListener('click', () => this.saveSettings());

    // 应用配置相关事件
    const ollamaUrlInput = this.model.querySelector('#ollama-base-url');
    ollamaUrlInput.addEventListener('input', (e) => {
      this.settings.ollama.OLLAMA_BASE_URL = e.target.value;
    });

    const topPInput = this.model.querySelector('#top-p-input');
    const topPValue = this.model.querySelector('#top-p-value');
    topPInput.addEventListener('input', (e) => {
      topPValue.textContent = e.target.value;
      this.settings.ollama.parameters.top_p = parseFloat(e.target.value);
    });
    const topKInput = this.model.querySelector('#top-k-input');
    topKInput.addEventListener('input', (e) => {
      this.settings.ollama.parameters.top_k = parseInt(e.target.value);
    });

    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
      if (e.ctrlKey && e.key === ',') {
        e.preventDefault();
        this.show();
      }
      if (e.key === 'Escape' && this.isVisible()) {
        this.hide();
      }
    });
  }

  /**
   * 显示设置对话框
   */
  show() {
    if (!this.model) return;

    this.model.style.display = 'block';
    this.model.classList.add('model-show');

    // 聚焦到第一个输入元素
    const firstInput = this.model.querySelector('select, input, button');
    if (firstInput) {
      setTimeout(() => firstInput.focus(), 100);
    }
  }

  /**
   * 隐藏设置对话框
   */
  hide() {
    if (!this.model) return;

    this.model.classList.add('model-hide');

    setTimeout(() => {
      this.model.style.display = 'none';
      this.model.classList.remove('model-show', 'model-hide');
    }, 300);
  }

  /**
   * 检查对话框是否可见
   */
  isVisible() {
    return this.model && this.model.style.display === 'block';
  }

  /**
   * 刷新模型列表
   */
  async refreshModels() {
    const modelSelect = this.model.querySelector('#model-select');
    const refreshBtn = this.model.querySelector('#refresh-models-btn');

    try {
      // 显示加载状态
      refreshBtn.classList.add('loading');
      refreshBtn.disabled = true;
      modelSelect.innerHTML = '<option value="">🔄 加载中...</option>';

      // 获取模型列表
      const models = await window.electronAPI.getModels();

      // 更新模型选项
      modelSelect.innerHTML = '';
      if (models && models.length > 0) {
        models.forEach(model => {
          const option = document.createElement('option');
          option.value = model.name;
          option.textContent = `${model.name} (${this.formatSize(model.size)})`;
          modelSelect.appendChild(option);
        });

        // 选择当前设置的模型
        if (this.settings.model) {
          modelSelect.value = this.settings.model;
        }
      } else {
        modelSelect.innerHTML = '<option value="">❌ 未找到模型</option>';
      }
    } catch (error) {
      console.error('获取模型列表失败:', error);
      modelSelect.innerHTML = '<option value="">❌ 加载失败</option>';
      this.showNotification('获取模型列表失败', 'error');
    } finally {
      // 隐藏加载状态
      refreshBtn.classList.remove('loading');
      refreshBtn.disabled = false;
    }
  }

  /**
   * 格式化文件大小
   */
  formatSize(bytes) {
    if (!bytes) return '未知大小';

    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;

    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }

    return `${size.toFixed(1)} ${units[unitIndex]}`;
  }

  /**
   * 加载保存的设置
   */
  loadSettings() {
    try {
      const savedSettings = localStorage.getItem('ollamaSettings');
      if (savedSettings) {
        this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
      }

      // 应用设置到UI
      this.applySettingsToUI();
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  }  /**
   * 保存设置（合并了配置保存功能）
   */
  async saveSettings() {
    try {
      // 保存到本地存储
      localStorage.setItem('ollamaSettings', JSON.stringify(this.settings));

      // 通过统一的API更新所有设置和配置
      await window.electronAPI.updateSettings(this.settings);

      this.showNotification('设置已保存', 'success');

      // 触发设置更新事件
      document.dispatchEvent(new CustomEvent('settingsUpdated', {
        detail: this.settings
      }));

      // 保存成功后关闭设置窗口
      setTimeout(() => {
        this.hide();
      }, 500); // 延迟500ms关闭，让用户看到成功提示
    } catch (error) {
      console.error('保存设置失败:', error);
      this.showNotification('保存设置失败', 'error');
    }
  }
  /**
   * 应用设置到UI
   */
  applySettingsToUI() {
    if (!this.model) return;

    const temperatureInput = this.model.querySelector('#temperature-input');
    const temperatureValue = this.model.querySelector('#temperature-value');
    const maxLengthInput = this.model.querySelector('#max-length-input');
    const modelSelect = this.model.querySelector('#model-select');
    const ollamaUrlInput = this.model.querySelector('#ollama-base-url');
    const topPInput = this.model.querySelector('#top-p-input');
    const topPValue = this.model.querySelector('#top-p-value');
    const topKInput = this.model.querySelector('#top-k-input');

    if (temperatureInput) {
      temperatureInput.value = this.settings.ollama.parameters.temperature;
      temperatureValue.textContent = this.settings.ollama.parameters.temperature;
    }

    if (maxLengthInput) {
      maxLengthInput.value = this.settings.ollama.parameters.max_length;
    }

    if (modelSelect && this.settings.ollama.model) {
      modelSelect.value = this.settings.ollama.model;
    }

    if (ollamaUrlInput) {
      ollamaUrlInput.value = this.settings.ollama.OLLAMA_BASE_URL;
    }

    if (topPInput) {
      topPInput.value = this.settings.ollama.parameters.top_p;
      topPValue.textContent = this.settings.ollama.parameters.top_p;
    }

    if (topKInput) {
      topKInput.value = this.settings.ollama.parameters.top_k;
    }
  }
  /**
   * 从应用配置加载设置
   */
  async loadConfigFromFile(showNotification = false) {
    try {
      const config = await window.electronAPI.getSettings();
      if (config) {
        this.config = { ...this.config, ...config };
      }
    } catch (error) {
      console.error('加载配置文件失败:', error);
      if (showNotification) {
        this.showNotification('加载配置文件失败', 'error');
      }
    }
  }

  /**
   * 深度合并对象
   */
  deepMerge(target, source) {
    const output = Object.assign({}, target);
    if (this.isObject(target) && this.isObject(source)) {
      Object.keys(source).forEach(key => {
        if (this.isObject(source[key])) {
          if (!(key in target))
            Object.assign(output, { [key]: source[key] });
          else
            output[key] = this.deepMerge(target[key], source[key]);
        } else {
          Object.assign(output, { [key]: source[key] });
        }
      });
    }
    return output;
  }

  /**
   * 检查是否为对象
   */
  isObject(item) {
    return item && typeof item === 'object' && !Array.isArray(item);
  }

  /**
   * 显示通知
   */
  showNotification(message, type = 'info') {
    // 这里可以调用全局的通知系统
    if (window.showNotification) {
      window.showNotification(message, type);
    } else {
      console.log(`${type.toUpperCase()}: ${message}`);
    }
  }
}

// 导出设置组件类
window.SettingsModel = SettingsModel;
